package xyz.liut.customview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;

import xyz.liut.liutlibraries.LiutUtils;
import xyz.liut.liutlibrarys.R;

/**
 * Created by liut on 16-9-13.
 * LineView
 */
public class LineView extends View {

    private final int DEFAULT_LINE_COLOR = 0xffdfdfdf;      //默认颜色
    private final float DEFAULT_LINE_MARGIN = 0;            //默认pidding

    private int lineColor;                                  //颜色
    private float lineMargin;                               //margin
    private boolean lineDashed;                             //是否是虚线 默人为否

    public LineView(Context context) {
        super(context);
    }

    public LineView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.LineView);
        lineColor = ta.getColor(R.styleable.LineView_line_color, DEFAULT_LINE_COLOR);
        lineMargin = ta.getDimension(R.styleable.LineView_line_margin, DEFAULT_LINE_MARGIN);
        lineDashed = ta.getBoolean(R.styleable.LineView_line_dashed, false);
        ta.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int wid = MeasureSpec.getSize(widthMeasureSpec);
        setMeasuredDimension(wid, measureH(heightMeasureSpec));
    }

    private int measureH(int heightMeasureSpec) {
        int result;
        int mode = MeasureSpec.getMode(heightMeasureSpec);
        int spec = MeasureSpec.getSize(heightMeasureSpec);

        switch (mode) {
            default:
            case MeasureSpec.EXACTLY:
                result = spec;
                break;
            case MeasureSpec.AT_MOST:
                result = Math.min(LiutUtils.dpToPx(getContext(), 1), spec);
                break;
            case MeasureSpec.UNSPECIFIED:
                result = Math.min(LiutUtils.dpToPx(getContext(), 1), spec);
                break;

        }
        return result;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Paint paint = new Paint();
        paint.setColor(lineColor);
        paint.setStrokeWidth(getHeight());
        paint.setStyle(Paint.Style.FILL_AND_STROKE);

        if (lineDashed) {
            paint.setPathEffect(new DashPathEffect(new float[]{8, 8}, 0));
            Path path = new Path();
            path.moveTo(lineMargin, getHeight() / 2);
            path.lineTo(getWidth() - lineMargin, getHeight() / 2);
            canvas.drawPath(path, paint);
        } else {
            canvas.drawLine(lineMargin,
                    getHeight() / 2,
                    getWidth() - lineMargin,
                    getHeight() / 2,
                    paint);
        }
    }
}


